import 'package:flutter_network/dio_manager.dart';

import '../../../log_util.dart';
import 'options.dart';

/// @author: pengboboer
/// @createDate: 2022/1/11
const FIRST_PAGE = 1;

class BasePagerRepository<D, T extends BasePagerBean<D>> {
  final PagerOptions<T> pagerOptions;
  final RefreshOptions<D> refreshOptions;

  BasePagerRepository(
      {required this.pagerOptions, required this.refreshOptions});

  /// 当前页
  int _currentPage = FIRST_PAGE;

  /// 需要请求的页
  int _requestPage = 1;

  /// 请求中
  bool _requesting = false;

  /// 没有更多数据
  bool _noMoreData = false;

  List<D> _data = [];

  refresh() {
    if (_requesting) return;
    _requestPage = FIRST_PAGE;
    _request(true);
  }

  loadMore() {
    if (_requesting) return;
    if (_noMoreData) {
      refreshOptions.onNoMoreData(true);
      return;
    }
    _requestPage = _currentPage + 1;
    _request(false);
  }

  _request(bool refresh) {
    dynamic resp = pagerOptions.requestProvider(_requestPage);
    _noMoreData = false;
    _requesting = true;
    resp.then((response) {
      _onSucceed(response, refresh);
    }).catchError((error) {
      LogUtils.d("分页请求失败: $error");
      _onFailed(refresh, "请求失败");
    });
  }

  _onSucceed(Response response, bool refresh) {
    T? data = pagerOptions.parseData(response);
    if (data != null && data.getOptions().isSucceed()) {
      // 请求成功才能确定当前页，避免本地一直重复累加页数
      _checkCurrentPage(data);
      _checkNoMoreData(data);
      refreshOptions.onNoMoreData(_noMoreData);
      _onFinish(refresh);
      if (refresh) _data.clear();
      _data.addAll(data.getOptions().getListData() ?? []);
      refreshOptions.onGetPageData(_data);
    } else {
      _onFailed(refresh, data?.getOptions().getMessage() ?? "");
    }
  }

  _onFailed(bool refresh, String message) {
    refresh
        ? refreshOptions.onRefreshError(message)
        : refreshOptions.onRefreshError(message);
    _onFinish(refresh);
  }

  _onFinish(bool refresh) {
    _requesting = false;
    refresh ? refreshOptions.onFinishRefresh() : refreshOptions.onFinishLoad();

    refreshOptions.onCurrentPage(_currentPage);
  }

  _checkCurrentPage(T data) {
    // 优先取网络请求获得的数据，如果后台没有返回当前页，则本地++
    _currentPage = data.getOptions().getCurrentPage() ?? _requestPage;
  }

  _checkNoMoreData(T data) {
    // 如果可以知道总的页数，那么超出总页数即没有更多数据
    if (data.getOptions().getTotalPage() != null) {
      _noMoreData = _currentPage >= data.getOptions().getTotalPage()!;
      // 如果不知道总的页数，那么只能判断当前的list的长度是否和pageSize相同
    } else {
      _noMoreData =
          (data.getOptions().getListData()?.length ?? 0) < (data.getOptions().getRequestPageSize() ?? 10);
    }
  }
}
